﻿using UnityEngine;

public class Record : MonoBehaviour
{

}
/*#region 模块信息
// **********************************************************************
// Copyright (C) 2018 Blazors
// Please contact me if you have any questions
// File Name:  VoiceChat
// Author:  romantic123fly
// WeChat||QQ:  at853394528 || 853394528 
// **********************************************************************
#endregion

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;


//此脚本须挂在录音按钮上
public class Record : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    public MyPostAndGet _myPostAndGet;
    float tirecordingTimemer = 0;//录音时长限制
    public AudioSource aud;//存储声音
    public audioClip audioClip;
    public Text ShowTimeHint;//剩余时间的文字提示
    public static string base64Str = "";
    //音频文件保存部分
    public Text Adress;//音频保存地址
    private string fileName;//保存的文件名
    private byte[] data;

    private void Start()
    {
        audioClip = aud.clip;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        Debug.C000000_Log("Start");
        StartCoroutine("KeepTime");
        audioClip = Microphone.Start(null, false, 10, 16000);
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        data = GetRealAudio(ref audioClip);

        Microphone.End("Built-in Microphone");

        StopCoroutine("KeepTime");
        // Debug.C000000_Log("Over");
        aud.clip = audioClip;
        aud.PlayAudioClip();
    }
    //此处开携程也行，用while也可以，放在updata里也没问题
    IEnumerator KeepTime()
    {
        for (tirecordingTimemer = 10; tirecordingTimemer >= 0; tirecordingTimemer -= Time.deltaTime)
        {
            if (tirecordingTimemer <= 10)
            {
                ShowTimeHint.text = "你还可以录 " + (int)tirecordingTimemer + " 秒";
                if (tirecordingTimemer < 1)
                {
                    ShowTimeHint.text = "时间到";
                    Microphone.End("Built-in Microphone");
                }
            }
            yield return 0;
        }
    }
    /// <summary>
    /// 保存录音
    /// </summary>
    public void Save()
    {

        if (!Microphone.NotRecording("Built-in Microphone"))
        {
            //Debug.C000000_Log("OK!!!");
            fileName = DateTime.Now.ToString("我也不知道叫什么名称比较好");
            if (!fileName.ToLower().EndsWith(".wav"))
            {//如果不是“.wav”格式的，加上后缀
                fileName += ".wav";
            }
            string path = Path.Combine("C:\\Users\\admin\\Desktop\\新建文件夹 (3)", fileName);//录音保存路径
            //print(path);//输出路径
            Adress.text = path;
            using (FileStream fs = CreateEmpty(path))
            {

                fs.Write(data, 0, data.Length);
                //Debug.C000000_Log(fs.Length);
                WriteHeader(fs, aud.clip); //wav文件头
            }
            //将WAV转成base64
            ReadFromFile(path);
            //todo
            _myPostAndGet.StartPost(16000, "zh-cmn-Hans-CN", base64Str);
        }

    }
    /// <summary>
    /// 获取真正大小的录音
    /// </summary>
    /// <param name="recordedClip"></param>
    /// <returns></returns>
    public static byte[] GetRealAudio(ref audioClip recordedClip)
    {
        int position = Microphone.GetPosition(null);
        if (position <= 0 || position > recordedClip.samples)
        {
            position = recordedClip.samples;
        }
        float[] soundata = new float[position * recordedClip.channels];
        recordedClip.GetData(soundata, 0);
        recordedClip = audioClip.Create(recordedClip.name, position,
        recordedClip.channels, recordedClip.frequency, false);
        recordedClip.SetData(soundata, 0);
        int rescaleFactor = 32767;
        byte[] outData = new byte[soundata.Length * 2];
        for (int i = 0; i < soundata.Length; i++)
        {
            short temshort = (short)(soundata[i] * rescaleFactor);
            byte[] temdata = BitConverter.GetBytes(temshort);
            outData[i * 2] = temdata[0];
            outData[i * 2 + 1] = temdata[1];
        }
        //Debug.C000000_Log("position=" + position + "  outData.leng=" + outData.Length);
        return outData;
    }
    /// <summary>
    /// 写文件头
    /// </summary>
    /// <param name="stream"></param>
    /// <param name="clip"></param>
    public static void WriteHeader(FileStream stream, audioClip clip)
    {
        int hz = clip.frequency;

        int channels = clip.channels;
        int samples = clip.samples;

        stream.Seek(0, SeekOrigin.Begin);

        Byte[] riff = System.Text.Encoding.UTF8.GetBytes("RIFF");
        stream.Write(riff, 0, 4);

        Byte[] chunkSize = BitConverter.GetBytes(stream.Length - 8);
        stream.Write(chunkSize, 0, 4);

        Byte[] wave = System.Text.Encoding.UTF8.GetBytes("WAVE");
        stream.Write(wave, 0, 4);

        Byte[] fmt = System.Text.Encoding.UTF8.GetBytes("fmt ");
        stream.Write(fmt, 0, 4);

        Byte[] subChunk1 = BitConverter.GetBytes(16);
        stream.Write(subChunk1, 0, 4);

        UInt16 one = 1;
        UInt16 two = 2;

        Byte[] audioFormat = BitConverter.GetBytes(one);
        stream.Write(audioFormat, 0, 2);

        Byte[] numChannels = BitConverter.GetBytes(channels);
        stream.Write(numChannels, 0, 2);

        Byte[] sampleRate = BitConverter.GetBytes(hz);
        stream.Write(sampleRate, 0, 4);

        Byte[] byteRate = BitConverter.GetBytes(hz * channels * 2);
        stream.Write(byteRate, 0, 4);

        UInt16 blockAlign = (ushort)(channels * 2);
        stream.Write(BitConverter.GetBytes(blockAlign), 0, 2);

        UInt16 bps = 16;
        Byte[] bitsPerSample = BitConverter.GetBytes(bps);
        stream.Write(bitsPerSample, 0, 2);

        Byte[] datastring = System.Text.Encoding.UTF8.GetBytes("data");
        stream.Write(datastring, 0, 4);

        Byte[] subChunk2 = BitConverter.GetBytes(samples * channels * 2);
        stream.Write(subChunk2, 0, 4);
    }
    /// <summary>
    /// 创建wav格式文件头
    /// </summary>
    /// <param name="filepath"></param>
    /// <returns></returns>
    private FileStream CreateEmpty(string filepath)
    {
        FileStream fileStream = new FileStream(filepath, FileMode.Create);
        byte emptyByte = new byte();

        for (int i = 0; i < 44; i++) //为wav文件头留出空间
        {
            fileStream.WriteByte(emptyByte);
        }

        return fileStream;
    }
    private static void ReadFromFile(string filepath)
    {
        FileStream fsForRead = new FileStream(filepath, FileMode.Open);

        try
        {
            //读入一个字节
            Console.Write("文件的第一个字节为：" + fsForRead.ReadByte().ToString());
            Console.ReadLine();
            //读写指针移到距开头10个字节处
            fsForRead.Seek(0, SeekOrigin.Begin);
            byte[] bs = new byte[fsForRead.Length];
            int log = Convert.ToInt32(fsForRead.Length);
            //从文件中读取10个字节放到数组bs中
            fsForRead.Read(bs, 0, log);
            base64Str = Convert.ToBase64String(bs);

            //Debug.C000000_Log("base64编码：" + base64Str);
            Console.ReadLine();
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
            Console.ReadLine();
        }
        finally
        {
            fsForRead.Close();
        }

    }

}
*/